package com.atjava.webspider.thread;

import java.util.List;

import com.atjava.webspider.consts.Const;
import com.atjava.webspider.gui.SpiderMainGui;
import com.atjava.webspider.gui.table.DefaultTableModel;
import com.atjava.webspider.model.Task;

/**
 * 任务表格监听器
 * @author kyo
 *
 */
public class TaskListener extends Thread{

	private boolean start;
	
	private Object lock = new Object();
	
	private SpiderMainGui mainGui;
	
	public TaskListener (SpiderMainGui mainGui){
		this.mainGui = mainGui;
	}
	
	public void run(){
		try {
			while(true){
				if(start){
					synchronized(lock){
						lock.wait();
					}
				}
				Thread.sleep(1000);
				List<Task> taskList = mainGui.getCurrentTaskList();
				if(taskList == null)
					continue;
				int n = mainGui.getJTableTaskList().getSelectedRow();
				for (int i = 0; i < taskList.size(); i++) {
					Task t = taskList.get(i);
					synchronized(t){
						t.setIndex(i);
						updateTaskRow(t);
					}
				}
				//恢复选中行
				if(n >= 0)
					mainGui.getJTableTaskList().setRowSelectionInterval(n, n);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void pause(){
		start = true;
	}
	
	public void goon(){
		start = false;
		synchronized(lock){
			lock.notify();
		}
	}

	public void updateTaskRow(Task task){
		int state = task.getState();
		int index = task.getIndex();
		if (index < 0)
			return ;
		DefaultTableModel tModel = mainGui.getTaskModel();
		switch(state){
			//已开始，正在下载
			case Const.TASK_STATE_DOWNING:
				//监听数据量
				tModel.updateData(index, 3,String.valueOf(task.getDataNum()));
				//监听时间
				tModel.updateData(index, 5,task.getPassedTime());
				//开始时间
				tModel.updateData(index, 4,task.getStartTimeStr());
				//监听时间
				tModel.updateData(index, 1,Const.getTaskStateName(task.getState()));
				break;
			//已完成
			case Const.TASK_STATE_FINISHED:
				break;
		}
		//任务状态
		tModel.updateData(index, 1,task.getStateName());
	}
}
